package cn.bluethink.eguan.core.service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

import cn.bluethink.eguan.core.entity.EgGoodsEntity;
import cn.bluethink.eguan.core.mapper.EgGoodsMapper;
import cn.bluethink.eguan.filter.IDFilter;
import cn.bluethink.eguan.model.core.EgGoods;
import cn.bluethink.eguan.model.core.EgOType;
import cn.bluethink.eguan.result.PageInfo;
import cn.bluethink.eguan.utils.IdMakerUtils;
import tk.mybatis.mapper.entity.Example;

/**
 * 商品业务层
 * 
 * @author 苏州中科蓝迪公司所有(c)2016-2021
 * @version 0.3.0
 * @brief 驿馆+产品
 * @note 修订历史： 1.wanglei于2018/11/26设计并构建初始版本v0.3.0
 */
@Service
public class EgGoodsService {

    @Autowired
    private EgGoodsMapper goodsMapper;

    private IdMakerUtils idMakerUtil = new IdMakerUtils();

    /**
     * 添加商品(标题、兑换价格、数量、图片)
     * 
     * @param goods
     * @param uid
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public EgGoods create(EgGoods goods, Long uid) throws Exception {
        goods.setId(idMakerUtil.nextId());
        EgGoodsEntity entity = new EgGoodsEntity(goods, uid);
        int insertCount = goodsMapper.insertSelective(entity);
        if (insertCount == 0) {
            return null;
        }
        return entity.createEgGoods();
    }

    /**
     * 删除商品
     * 
     * @param gdid
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public Boolean del(Long gdid) throws Exception {
        int delCount = goodsMapper.deleteByPrimaryKey(gdid);
        if (delCount == 0) {
            throw new RuntimeException("删除失败！");
        }
        return true;
    }

    /**
     * 编辑商品(标题、兑换价格、数量、图片) 乐观锁控制商品的数量增减情况
     * 
     * @param oldGoods
     * @param goods
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public EgGoods update(EgGoods oldGoods, EgGoods goods) throws Exception {
        if (goods != null) {
            if (goods.getName() != null) {
                oldGoods.setName(goods.getName());
            }
            if (goods.getIcon() != null) {
                oldGoods.setIcon(goods.getIcon());
            }
            // 待更新的价格,数量
            Integer upPricae = goods.getPrice() == null ? oldGoods.getPrice() : goods.getPrice();
            Integer upNumber = goods.getNumber() == null ? oldGoods.getNumber() : goods.getNumber();
            oldGoods.setPrice(upPricae);
            oldGoods.setNumber(upNumber);
            // 编辑商品的剩余数量
            oldGoods.setRemain(upNumber);
        }
        EgGoodsEntity entity = new EgGoodsEntity(oldGoods);
        Example example = new Example(EgGoodsEntity.class);
        example.and().andEqualTo("gdid", oldGoods.getId()).andEqualTo("utime", oldGoods.getUtime());
        int updateCount = goodsMapper.updateByExampleSelective(entity, example);
        if (updateCount == 0) {
            return null;
        }
        return entity.createEgGoods();
    }

    /**
     * 根据主键获取商品的详情
     * 
     * @param gdid
     * @return
     * @throws Exception
     */
    public EgGoods detail(Long gdid) throws Exception {
        EgGoodsEntity entity = goodsMapper.selectByPrimaryKey(gdid);
        return entity != null ? entity.createEgGoods() : null;
    }

    /**
     * 根据包裹ID获取未兑换的（Remain>0）商品列表
     * 
     * @param bagid
     * @return
     * @throws Exception
     */
    public List<EgGoods> getGoodsList(Long bagid) throws Exception {
        Example example = new Example(EgGoodsEntity.class);
        example.and().andEqualTo("bagid", bagid);
        List<EgGoodsEntity> entitites = goodsMapper.selectByExample(example);
        List<EgGoods> result = new ArrayList<>();
        if (entitites != null && entitites.size() > 0) {
            result = entitites.stream().filter(g -> g.getRemain() > 0).map(g -> g.createEgGoods())
                    .collect(Collectors.toList());
        }
        return result;
    }

    /**
     * 根据包裹ID删除该包裹里的所有商品列表
     * 
     * @param bagid
     * @return
     * @throws Exception
     */
    public Boolean delGoodsList(Long bagid) throws Exception {
        Example example = new Example(EgGoodsEntity.class);
        example.and().andEqualTo("bagid", bagid);
        int delCount = goodsMapper.deleteByExample(example);
        return delCount > 0 ? true : false;
    }

    /**
     * 过滤查询商品列表。
     * 根据商品的所有者（神秘商人）查询
     * 
     * @param filter
     * @return
     * @throws Exception
     */
    public PageInfo<EgGoods> query(IDFilter filter) throws Exception {
        Integer pageNum = filter.getPageNum() == null ? 1 : filter.getPageNum();
        Integer pageSize = filter.getPageSize() == null ? 50 : filter.getPageSize();
        // 构造查询条件
        String whereSql = buildQuerySql(filter);
        // 返回结果
        List<EgGoods> result = new ArrayList<>();
        List<EgGoodsEntity> entities = new ArrayList<>();
        // 判断whereSql不为空，根据条件查询
        if (whereSql != null && !"".equals(whereSql)) {
            // 分页
            PageHelper.startPage(pageNum, pageSize);
            entities = goodsMapper.selectGoodsByCondition(whereSql);
        }
        PageInfo<EgGoodsEntity> oldPageInfo = new PageInfo<>(entities);
        if (entities != null && entities.size() > 0) {
            result = entities.stream().map(g -> g.createEgGoods()).collect(Collectors.toList());
        }
        return new PageInfo<>(result, oldPageInfo);
    }

    /**
     * 构建query查询条件
     * 
     * @param filter
     * @return
     * @throws Exception
     */
    private String buildQuerySql(IDFilter filter) throws Exception {
        String whereSql = "";
        List<String> whereSqlList = new ArrayList<>();
        // 获取对象类型ID
        Long id = filter.getId() == null ? 0 : filter.getId();
        Boolean buid = filter.getBuid() == null ? false : filter.getBuid();

        whereSqlList.add(" 1 = 1 ");
        // 根据商品的所有者（神秘商人类型ID以及神秘商人的ID）进行查询(商人未删除)
        if (id > 0 && !buid) {
            whereSqlList.add(" G.owner_otype = " + EgOType.TRADER);
            whereSqlList.add(" G.owner_oid = " + id);
            whereSqlList.add(" T.delete_flag = 0 ");
        }
        // 设置查询条件AND连接符
        if (whereSqlList.size() > 0) {
            whereSql += String.join(" AND ", whereSqlList);
        }
        // 按照创建时间正序排序
        whereSql += " ORDER BY G.ctime ";
        return whereSql;
    }

}
